package com.software.myopiachildren.ui.login;


import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.software.myopiachildren.App;
import com.software.myopiachildren.MainActivity;
import com.software.myopiachildren.R;
import com.software.myopiachildren.base.BaseActivity;
import com.software.myopiachildren.bean.LoginInfo;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.http.HostType;
import com.software.myopiachildren.http.HttpApi2;
import com.software.myopiachildren.ui.HelpActivity;
import com.software.myopiachildren.utils.RegexUtils;
import com.software.myopiachildren.utils.ToastUtil;
import com.software.myopiachildren.utils.perm.NetworkUtils;
import com.software.myopiachildren.utils.sp.SP;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 登录页
 *
 * @author penglei
 * @date 2020/05/12
 */
public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    @BindView(R.id.tv_help)
    TextView mTvHelp;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.btn_login)
    Button mBtnLogin;
    @BindView(R.id.tv_register)
    TextView mTvRegister;
    @BindView(R.id.tv_forget_pwd)
    TextView mTvForgetPwd;
    @BindView(R.id.iv_login_wechat)
    ImageView mIvLoginWechat;
    @BindView(R.id.ll_login_wechat)
    LinearLayout mLlLoginWechat;
    @BindView(R.id.iv_login_qq)
    ImageView mIvLoginQq;
    @BindView(R.id.ll_login_qq)
    LinearLayout mLlLoginQq;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @OnClick({R.id.tv_help, R.id.btn_login, R.id.tv_register, R.id.tv_forget_pwd, R.id.iv_login_wechat, R.id.iv_login_qq})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_help:
                startActivity(new Intent(this, HelpActivity.class));
                break;

            case R.id.btn_login:
                getLogin();
                break;

            case R.id.tv_register:
                startActivity(new Intent(this, RegisterActivity.class));
                break;

            case R.id.tv_forget_pwd:
                startActivity(new Intent(this, ForgetpwdActivity.class));
                break;

            case R.id.iv_login_wechat:
                authorization(2, SHARE_MEDIA.WEIXIN);
                break;

            case R.id.iv_login_qq:
                authorization(1, SHARE_MEDIA.QQ);
                break;
        }
    }


    /**
     * 登录
     */
    private void getLogin() {
        String account = mEtPhone.getText().toString().trim();
        String pwd = mEtPassword.getText().toString().trim();
        //验证手机号/邮箱
        if (TextUtils.isEmpty(account)) {
            ToastUtil.showShort(getString(R.string.toast_username_empty));
            return;
        }
        if (RegexUtils.checkEmail(account) || RegexUtils.checkTelephone(account)) {

        } else {
            ToastUtil.showShort(getString(R.string.toast_username_error));
            return;
        }

        //验证密码
        if (!RegexUtils.isPassword(this, pwd)) {
            return;
        }

        if (NetworkUtils.isConnected(LoginActivity.this)) {
            Map<String, String> params = new HashMap<>();
            params.put("account", account);
            params.put("password", pwd);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getLogin(params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<LoginInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(LoginInfo loginInfo) {
                            try {
                                Log.e(TAG, "===loginInfo:" + loginInfo.toString());
                                if (loginInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    App.user = loginInfo.getData(); // 用户参数
                                    App.token = App.user.getToken(); // 用户token
                                    App.jwt_token = App.user.getJwt_token(); // 用户jwt_token
                                    new SP().save(Constant.USER_ID, loginInfo.getData().getChildren_user_id());
                                    new SP().save(Constant.USER_TOKEN, loginInfo.getData().getToken());
                                    new SP().save(Constant.USER_JWT_TOKEN, loginInfo.getData().getJwt_token());
                                    new SP().save(Constant.USER_NAME, loginInfo.getData().getNickname());
                                    new SP().save(Constant.SP_USER_DATA, new Gson().toJson(loginInfo.getData()));
                                    new SP().save(Constant.DEVICE_CODE, loginInfo.getData().getDevice_code());  // 设备号
                                    new SP().save(Constant.BIND_DEVICE, loginInfo.getData().getHas_binding());  // 设备绑定
                                    new SP().save(Constant.CORR_DIS, loginInfo.getData().getSafe_distance());  // 矫正距离

                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    finish();
                                } else {
                                    ToastUtil.showShort(loginInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }

    }

    /**
     * 第三方登录获取信息 授权等
     */
    private void authorization(int type, SHARE_MEDIA share_media) {
        UMShareAPI.get(this).getPlatformInfo(this, share_media, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                Log.e(TAG, "===onStart: " + "授权开始");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
//                ToastUtil.showShort(getResources().getString(R.string.s_authorization_success));
                Log.e(TAG, "===onSuccess: " + "授权成功");
                Log.e(TAG, "===map:" + map.toString());
                String openid = map.get("uid");
                String nickName = map.get("name");
                String iconUrl = map.get("iconurl");
                Log.e(TAG, "===openid:" + openid);
                Log.e(TAG, "===nickName:" + nickName);
                Log.e(TAG, "===iconUrl:" + iconUrl);
                getThirdLogin(type, openid, nickName, iconUrl);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                ToastUtil.showShort(getResources().getString(R.string.s_authorization_error));
                Log.e(TAG, "===onError: " + "授权失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                ToastUtil.showShort(getResources().getString(R.string.s_authorization_cancel));
                Log.e(TAG, "===onCancel: " + "授权取消");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 第三方登陆接口
     */
    private void getThirdLogin(int type, String openId, String nickName, String iconUrl) {
        Map<String, String> params = new HashMap<>();
        params.put("openid", openId);
        params.put("name", nickName);
        params.put("type", type + "");

        HttpApi2.getApiService(HostType.TELE_CONFIG).getThirdLogin(params).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginInfo>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(Long.MAX_VALUE);
                    }

                    @Override
                    public void onNext(LoginInfo loginInfo) {
                        Log.e(TAG, "===registerInfo:" + loginInfo.toString());
                        if (loginInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                            if (loginInfo.getData().getHas_mobile() == 0){
                                startActivity(new Intent(LoginActivity.this, BindPhoneActivity.class));
                            }else {
                                App.user = loginInfo.getData(); // 用户参数
                                App.token = App.user.getToken(); // 用户token
                                App.jwt_token = App.user.getJwt_token(); // 用户jwt_token
                                new SP().save(Constant.USER_ID, loginInfo.getData().getChildren_user_id());
                                new SP().save(Constant.USER_TOKEN, loginInfo.getData().getToken());
                                new SP().save(Constant.USER_JWT_TOKEN, loginInfo.getData().getJwt_token());
                                new SP().save(Constant.USER_NAME, loginInfo.getData().getNickname());
                                new SP().save(Constant.SP_USER_DATA, new Gson().toJson(loginInfo.getData()));
                                new SP().save(Constant.DEVICE_CODE, loginInfo.getData().getDevice_code());  // 设备号
                                new SP().save(Constant.BIND_DEVICE, loginInfo.getData().getHas_binding()); // 设备绑定
                                new SP().save(Constant.CORR_DIS, loginInfo.getData().getSafe_distance());  // 矫正距离
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            }
                        } else {
                            ToastUtil.showShort(loginInfo.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Log.e(TAG, "===login_error:" + t.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
